<script setup>
import { ref, computed } from 'vue';
import emitter from '@/utils/bus';

const cartItems = ref([]);

// 监听添加商品事件
emitter.on('add-to-cart', (product) => {
  const existingItem = cartItems.value.find(item => item.id === product.id);
  if (existingItem) {
    existingItem.number++;
  } else {
    cartItems.value.push({ ...product, number: 1 });
  }
});

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.price * item.number, 0);
});

const handleChange = (item) => {
  if (item.number <= 0) {
    removeFromCart(item);
  }
};

const removeFromCart = (item) => {
  const index = cartItems.value.indexOf(item);
  if (index > -1) {
    cartItems.value.splice(index, 1);
  }
};

const clearCart = () => {
  cartItems.value = [];
};

const submitOrder = () => {
  // 提交订单逻辑
};
</script>

<template>
  <el-card style="margin-top: 10%">
    <h2><i class="fas fa-shopping-cart"></i> 购物车</h2>
    <div v-if="cartItems.length > 0">
      <div v-for="(item, i) in cartItems" :key="i">
        <div style="display: flex; flex-direction: row; align-items: center">
          <img :src="item.img" style="width: 50px; height: 50px" />
          {{ item.name }}
        </div>
        <div>
          <span style="margin-right: 9%">单价：￥{{ item.price }}</span>
          <el-input-number
            v-model="item.number"
            :min="0"
            :max="item.stock"
            @change="handleChange(item)"
          ></el-input-number>
          <el-divider style="margin: 10px 0" />
        </div>
      </div>
      <div style="text-align: right">
        <p>总价：￥{{ totalPrice }}</p>
        <el-button type="primary" plain @click="clearCart">清空购物车</el-button>
        <el-button type="primary" @click="submitOrder">结算</el-button>
      </div>
    </div>
    <div v-else>
      <el-empty description="暂无商品"></el-empty>
      <p>总价：￥{{ totalPrice }}</p>
      <el-button type="primary" @click="submitOrder">结算</el-button>
    </div>
  </el-card>
</template>